<?php
namespace App\Service;
use App\Exceptions\ApiException;
use App\Models\Common\ShareBackgroundImg;
use App\Models\User\SystemUser;
use App\Models\User\WithdrawalCash;
use App\Models\User\UserFile;
use App\Models\User\UserWalletrecord;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Intervention\Image\Facades\Image;

class UserService implements User {
    /**
     * 获取用户信息
     * @return mixed
     */
    public function info($user_id){

        $user = SystemUser::query()->findOrFail($user_id);
        return $user;

    }


    /**
     * 修改用户信息；
     * @return mixed
     */
    public function updateInfo(array $data, $user){

        $user = ojbectAssign($user, $data, $user->getFillable());

        return $boolean = $user->save();

    }


    /**
     * miniProgramLogin 小程序登录
     * @time:2020/2/5-12:05
     * @param $code  小程序码  测试码 111111
     * @param $parent_id 父级id default 0
     * @param $pass 通信码
     * @param $user_id  测试登录用户id
     * @author:dongdong
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response|mixed
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function miniProgramLogin($code, $parent_id, $user_id, $pass){
        if($parent_id) {
            $parent = SystemUser::query()->find($parent_id);
            if (!$parent) {
                Log::debug(' miniProgramLogin->登录-父级id不存在 ', request()->all());
                $parent_id = 0;
            }
        }

        if ($code == 111111 && $user_id && $pass == 'dongdongidea') {
            $user =  SystemUser::query()->findOrFail($user_id);
        }
        else {
            $config = config('wechat.mini_program.default');
            $app = Factory::miniProgram($config);
            $data = $app->auth->session($code);

            if(!isset($data['openid'])) {
               throw new ApiException('登录异常'.json_encode($data));
            }

            $openid = $data['openid'];

            if (!SystemUser::query()->where('openid',$openid)->exists()) {
                SystemUser::create([
                    'openid' => $openid,
                ]);
            }

            $user =  SystemUser::query()->where('openid',$openid)->firstOrFail();

            if (!$user->parent_id && $parent_id) {
                $user->parent_id = $parent_id;
                $user->save();
            }

        }
        $user->last_login = currentTimestamp();
        $token = auth('api')->login($user);
        $user->remember_token = $token;
        $user->save() ;

        return $token;
    }

    /**
     * 获取第一级全部子集
     * @return mixed
     */
    public function getFirstLevelChild(SystemUser $user){
        // 多级数据；
        $data = SystemUser::query()->where('parent_id', $user->id)->get();
        return $data;
    }
    /**
     * 获取第一级全部子集 【分页】
     * @param $user
     * @param $limit=15
     * @return mixed
     */
    public function getFirstLevelChildPaginate(SystemUser $user, $limit=15){
        // 多级数据；
        $data = SystemUser::query()
            ->where('parent_id', $user->id)
            ->paginate($limit);

        return $data;
    }

    /**
     * getParentInfo 获取父级用户
     * @time:2020/2/5-13:28
     * @param SystemUser $user
     * @author:dongdong
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
     */
    public function getParentInfo(SystemUser $user){
        if ($user->parent_id) {
            $parent = SystemUser::query()->find($user->parent_id);
            return $parent;
        }
        return null;
    }


    /**
     * getNearByDistance 获取附件的用户通过  经纬度；
     * @time:2020/2/5-13:43
     * @param $longitude  经度 赤道
     * @param $latitude 纬度 宽 竖线
     * @author:dongdong
     */
    public function getNearByDistance($longitude, $latitude, int $limitDistance=0)
    {

        $distance = 'ROUND(
            6378.138 * 2 * ASIN(SQRT(POW(SIN(('
                    .$latitude.' * PI() / 180 - latitude * PI() / 180) / 2),2) + COS('
                    .$latitude.' * PI() / 180) * COS(latitude * PI() / 180) * POW(SIN(('
                    .$longitude.' * PI() / 180 - longitude * PI() / 180) / 2),2))) * 1000)  '; //单位是米； “*1000”
        $query = SystemUser::query()->selectRaw("*,".$distance.'as diffdistance');

        if ($limitDistance) {
            $query->whereRaw($distance." <= ". $limitDistance);
        }

        $queryData = $query->paginate();
        return $queryData;
    }


    /**
     * saveUserFile 保存用户文件
     * @time:2020/2/17-15:20
     *
     * @param SystemUser $user
     * @param $fiels [file_type, file_url]
     * @author:dongdong
     */
    public function saveUserFile(SystemUser $user,$fiels)
    {
        $fileType = $fiels['file_url']??'default';
        $user->Fiels()->create([
            'file_type' =>$fileType,
            'file_url' => $fiels['file_url']
        ]);
    }


    /**
     * walletIncreaseRecord  钱包增加记录
     * @time:2020/2/17-16:02
     * @param SystemUser $user
     * @param  $type:
     * @author:dongdong
     */
    public function walletIncreaseRecord(SystemUser $user)
    {
        $data = $user->WalletRecord()
                ->where('direction', UserWalletrecord::DIRECTION_INCREASE)
                ->orderBy('created_at','desc')
                ->get();
        return $data;
    }

    /**
     * walletDecreaseRecord 钱包减少记录
     * @time:2020/2/17-18:29
     */
    public function walletDecreaseRecord(SystemUser $user)
    {
        $data = $user->WalletRecord()
            ->where('direction', UserWalletrecord::DIRECTION_INCREASE)
            ->orderBy('created_at','desc')
            ->get();
        return $data;
    }
    /**
     * withdrawalRecord 资金全部记录（流入，流出）
     * @time:2020/2/17-18:29
     */
    public function walletRecord(SystemUser $user)
    {
        $data = $user->WalletRecord()
            ->orderBy('created_at','desc')
            ->get();
        return $data;
    }

    /**
     * WalletApplyRecord 资金提现申请记录；
     * @time:2020/2/17-18:29
     */
    public function WalletApplyRecord(SystemUser $user)
    {
        $data = $user->WithdrawalCashRecord()
            ->where('status', WithdrawalCash::STATUS_ING)
            ->orderBy('created_at','desc')
            ->get();
        return $data;
    }

    /**
     * WalletApplyRecord 申请提现；
     * @param  $withdrawal_type 提现方式
     * @param $money 提现金额
     * @time:2020/2/17-18:29
     */
    public function WithdrawalApply(SystemUser $user, $money,$withdrawal_type ='wechat')
    {
        # 钱包记录+记录
        # 添加提现订单
        # 钱包扣钱
        DB::beginTransaction();
        $before_amount = $user->wallet;
        $user->wallet = $user->wallet - $money;
        if ($user->wallet<0) {
            throw new ApiException('钱包金额不足');
        }
        $user->save();
        $withdwalCash = $user->WithdrawalCashRecord()->create([
            'withdrawal_number' => makeNumber(),
            'content' => '提现',
            'money' => $money,
            'status' =>  WithdrawalCash::STATUS_ING,
            'withdrawal_type' => $withdrawal_type

        ]);

        $walletRecord = $user->WalletRecord()->create([
            'type_id' => $withdwalCash->id,
            'type' => 'withdrawal',
            'content' => '提现',
            'money' => $money,
            'direction' => UserWalletrecord::DIRECTION_INCREASE,
            'remaining_amount' => $user->wallet,
            'before_amount' => $before_amount,
        ]);
        DB::commit();
        return $walletRecord;
    }

    # 获取 多个推广分享图
    public function getMultipleShareimg()
    {
        $user =  Auth::user();
        $shareData = ShareBackgroundImg::query()->get();
        $param = "invitationno={$user->no}";

        $miniQrcode = $this->getMiniparamQrcode($param);

        $bg = public_path('static/bg-1.png');
        $fontPath = public_path().'/static/simkai.ttf';
        $text = $user->nickname.'邀请你加入...';
        $res  = [];
        $publicPath = public_path();
        $host = request()->getSchemeAndHttpHost();
        foreach ($shareData as $key=>$val) {
            $filename = "{$val->version}_{$key}_shareimg.png";
            $savepath = public_path()."/make/user/{$user->no}/";
            if (!is_dir($savepath)) {
                mkdir($savepath,0777,true);
            }
            if (file_exists($savepath.$filename)) {
                $res[]  = str_replace($publicPath, $host,$savepath.$filename);
                continue;
            }
            $image = Image::make($bg)
                ->insert($miniQrcode,'top-left',200,550)
                ->text($text, 180,1000, function ($font) use ($fontPath) {
                    $font->file($fontPath);
                    $font->size(30);
                    $font->color("#d10909");
                    $font->valign('center');
                })
                ->save($savepath.$filename);
            $res[]  = str_replace($publicPath, $host,$savepath.$filename);
        }
        return $res ;
    }

    # 生成小程序二维码  $param 32 个字符
    public function getMiniparamQrcode($param){
        if (strlen($param)>32) {
            throw new ApiException('二维码获取异常 字符参数超长(标准32个字符):'.$param);
        }
        $user =  Auth::user();
        $dir = public_path("make/{$user->id}");
        $str = $param;
        $filename = $str. '.png';
        $file =  $dir.'/'.$filename;
        if (file_exists($file)) {
            return $file;
        }
        $config = config('wechat.mini_program.default');
        $app = Factory::miniProgram($config);
        $response = $app->app_code->getUnlimit($param,[
            'page' => 'pages/case/case',
            'width' => 600,
        ]);

        // 保存小程序码到文件
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {

             $response->save($dir, $filename);

             return $file;
        }
        $error = json_encode($response);
        throw new ApiException('二维码获取异常'.$error);
    }

}
